package com.example.demo.service.impl;

import com.example.demo.entity.Goods;
import com.example.demo.entity.OrdersManagement;
import com.example.demo.entity.ShoppingCart;
import com.example.demo.entity.User;
import com.example.demo.mapper.GoodsMapper;
import com.example.demo.mapper.OrdersManagementMapper;
import com.example.demo.mapper.ShoppingCartMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.GoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 商品管理 服务实现类
 * </p>
 */
@Service
@Slf4j
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private OrdersManagementMapper ordersManagementMapper;

    @Override
    public List<Goods> getAllGoods() {
        return goodsMapper.selectAllGoods();
    }

    @Override
    public List<Goods> getGoodsByCategory(String category) {
        return goodsMapper.selectGoodsByCategory(category);
    }

    @Override
    public Goods getGoodsById(Integer id) {
        return goodsMapper.selectGoodsById(id);
    }

    @Override
    public List<String> getAllCategories() {
        return goodsMapper.selectAllCategories();
    }

    @Override
    public List<Goods> getUserGoods(Integer userId) {
        return goodsMapper.selectGoodsByUserId(userId);
    }

    // 当商品库存数大于一，下单后，该商品库存数减一，创建订单（订单状态为进行中）。卖方余额增加商品价格，买方余额减少商品价格，如果买方余额不足则提示“余额不足，不能购买此商品”，订单不创建。
    // 当商品库存数等于一，下单后，该商品库存数减一，创建订单（订单状态为进行中）。卖方余额增加商品价格，买方余额减少商品价格，如果买方余额不足则提示“余额不足，不能购买此商品”，订单不创建。
    @Override
    @Transactional(rollbackFor = Exception.class) // 确保所有异常都触发回滚
    public String createOrder(Integer userId, Integer goodsId, Integer quantity) {
        try {
            // 1. 获取商品信息
            Goods goods = goodsMapper.selectGoodsById(goodsId);
            if (goods == null) {
                throw new RuntimeException("商品不存在"); // 抛出异常
            }

            // 2. 检查库存 - 修改逻辑
            if (goods.getGStockQuantity() == 0 || goods.getGStockQuantity() < quantity) { // 简化条件
                throw new RuntimeException("库存不足");
            }

            // 3. 获取买家和卖家信息
            User buyer = userMapper.selectById(userId);
            User seller = userMapper.selectById(goods.getGUserId());

            if (buyer == null || seller == null) {
                throw new RuntimeException("用户信息错误");
            }

            // 4. 计算总金额
            BigDecimal totalAmount = goods.getGPrice().multiply(BigDecimal.valueOf(quantity));

            // 5. 检查买家余额
            if (buyer.getUBalance().compareTo(totalAmount) < 0) {
                throw new RuntimeException("余额不足，不能购买此商品");
            }

            // 6. 更新商品库存
            int newStock = goods.getGStockQuantity() - quantity;
            goods.setGStockQuantity(newStock);
            goodsMapper.updateById(goods);  // 确保库存更新

            // 7. 更新买家和卖家余额
            buyer.setUBalance(buyer.getUBalance().subtract(totalAmount));
            seller.setUBalance(seller.getUBalance().add(totalAmount));

            userMapper.updateById(buyer);
            userMapper.updateById(seller);

            // 8. 创建订单
            OrdersManagement order = new OrdersManagement();
            order.setOGoodsId(goodsId);
            order.setOUserIdOne(seller.getUId()); // 卖家ID
            order.setOUserIdTwo(userId);         // 买家ID
            order.setOTotalAmount(totalAmount);
            order.setOStatus("进行中");
            order.setOCreateTime(new Date());

            ordersManagementMapper.insert(order);

            return "下单成功";
        } catch (RuntimeException e) {
            // 记录错误日志
            log.error("创建订单失败: {}", e.getMessage());
            // 抛出异常确保事务回滚
            throw e;
        }
    }

    @Override
    @Transactional
    public String addToCart(Integer userId, Integer goodsId, Integer quantity) {
        Goods goods = goodsMapper.selectGoodsById(goodsId);
        if (goods == null) {
            return "商品不存在";
        }

        ShoppingCart otherCartItem = shoppingCartMapper.selectByUserAndGoods(
                userId, goodsId);

        if (otherCartItem != null) {
            if (goods.getGStockQuantity() < quantity + shoppingCartMapper.countByGoodsIdAndUserId(goodsId, userId)) {
                throw new RuntimeException("添加商品到购物车的数量不能超过库存！");
            }
            // 更新数量
            shoppingCartMapper.updateQuantityByUserIdAndGoodsId(otherCartItem.getSUserId(), otherCartItem.getSGoodsId(), otherCartItem.getSQuantity() + quantity);
            return "购物车商品数量已更新";
        } else {
            // 添加到购物车
            ShoppingCart cartItem = new ShoppingCart();
            cartItem.setSUserId(userId);
            cartItem.setSGoodsId(goodsId);
            cartItem.setSQuantity(quantity);
            cartItem.setSAddTime(new Date());

            // 添加新商品
            shoppingCartMapper.insert(cartItem);
            return "商品已添加到购物车";
        }
    }

    @Override
    @Transactional
    public Goods createGoods(Goods goods) {
        // 设置商品状态
        goods.setGIsActive(true);
        goods.setGIsTrade(false);
        goods.setGCreateTime(new Date());

        // 插入商品
        goodsMapper.insert(goods);
        return goods;
    }

    public void deleteGoods(Integer id) {
        Goods goods = goodsMapper.selectById(id);
        if (goods == null) {
            throw new RuntimeException("商品不存在");
        }
        goodsMapper.deleteById(id);
    }

    public void updateGoodsStatus(Integer id, Boolean active) {
        Goods goods = goodsMapper.selectById(id);
        if (goods == null) {
            throw new RuntimeException("商品不存在");
        }
        goods.setGIsActive(active);
        goodsMapper.updateById(goods);
    }

    @Override
    @Transactional
    public Goods updateGoods(Goods updatedGoods) {
        // 1. 检查商品是否存在
        Goods existingGoods = goodsMapper.selectById(updatedGoods.getGId());
        if (existingGoods == null) {
            throw new RuntimeException("商品不存在");
        }

        // 2. 更新允许修改的字段
        existingGoods.setGName(updatedGoods.getGName());
        existingGoods.setGPrice(updatedGoods.getGPrice());
        existingGoods.setGStockQuantity(updatedGoods.getGStockQuantity());
        existingGoods.setGCategory(updatedGoods.getGCategory());
        existingGoods.setGDescription(updatedGoods.getGDescription());

        // 3. 保存更新
        goodsMapper.updateById(existingGoods);

        // 4. 返回更新后的商品
        return existingGoods;
    }
}
